package com.example.servlet.manager;

import com.example.email.EmailSender;
import com.example.entity.Passenger;
import com.example.entity.Ticket;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/manager_delay_flight")
public class mDelayFlightServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String flightId = req.getParameter("flightId");

        if (flightId == null || flightId.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少航班ID");
            return;
        }
        String numberPart = flightId.replaceAll("\\D+", ""); // 移除所有非数字字符
        int idNumber = Integer.parseInt(numberPart);


        try{
            //改航班状态
            if(service.delayFlightStatusByFlightId(idNumber)==0){
                throw new Exception("Failed to delay flight");
            }
            //改机票状态
            service.delayTicketByFlightId(idNumber);
            service.commit();
            req.getSession().setAttribute("delay_success", new Object());
            List<Ticket> tickets = service.getTicketsByFlightId(idNumber);
            for (Ticket ticket : tickets) {
                String email = service.getEmailByPassengerId(ticket.getPassenger_id());
                if (email != null && !email.isEmpty()) {
                    EmailSender.sendDelayNotification(email, flightId); // 调用发送邮件方法
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("delay_failure", new Object());
            resp.sendRedirect("manager_flight");
        }
        // 返回成功响应
        resp.setContentType("text/plain");
        resp.getWriter().write("航班已删除: " + flightId);
    }
}
